package com.youwe.dao.demo;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.youwe.dao.common.BaseDao;
import com.youwe.interfaces.dao.demo.UserDao;
import com.youwe.model.common.PageModel;
import com.youwe.model.demo.User;

@Repository
public class UserDaoImpl extends BaseDao implements UserDao {

	@Autowired
	private MongoOperations mongoTemplate;

	public void insertUser(User user) {
		mongoTemplate.save(user);
	}

	public User findUser(User user) {
		Query query = new Query(Criteria.where("id").is(user.getId()));
		return mongoTemplate.findOne(query, User.class);
	}

	public void updateUser(User user) {
		Query query = new Query(Criteria.where("id").is(user.getId()));
		Update update = new Update().set("name", user.getName()).set("password", user.getPassword());
		mongoTemplate.updateFirst(query, update, User.class);
	}

	public void deleteUser(User user) {
		Query query = new Query(Criteria.where("id").is(user.getId()));
		mongoTemplate.remove(query, User.class);
	}
	
	@SuppressWarnings("all")
	public PageModel<User> findUserByAttribute(User user, PageModel<User> page) {
		/**
		 * 构造查询语语
		 */
		Query query = new Query();
		
		/**
		 * 构造查询条件
		 */
		Criteria criteria = new Criteria();
		List<Order> orders = new ArrayList<Order>();
		criteria.and("age").is(18);
		criteria.and("address").regex("\".*?\"+\"shenzhen\"+\".*\"");
		
		/**
		 * 构造排序信息
		 */
		orders.add(new Order(Direction.DESC, "age"));
		
		return super.paginationQuery(query, criteria, orders, page, User.class);
		
	}

}
